package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author mengwei
 * @date 2019/8/18
 * @desc
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    OrderService orderService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,Object> map){
        try {
            //获取手机号
            String telephone = String.valueOf(map.get("telephone"));
            //获取用户输入的验证码
            String validateCodeRedis = String.valueOf(map.get("validateCode"));
            //从redis中获取存入的验证码
            String validateCodeUser = jedisPool.getResource().get(RedisConst.SENDTYPE_ORDER + "-" + telephone);
            if (validateCodeRedis == null || !validateCodeRedis.equals(validateCodeUser)){
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
            //加入预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            //添加预约信息
            Result result = orderService.addOrder(map);
            //预约成功，发送通知短信
            if (result.isFlag()){

            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ORDER_FAIL);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> map = orderService.findById(id);
            Date date = (Date) map.get("orderDate");
            String orderDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
            map.put("orderDate",orderDate);
            return new Result(true,MessageConst.GET_ORDERSETTING_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_ORDERSETTING_FAIL);
        }
    }
}
